from http.server import HTTPServer, BaseHTTPRequestHandler
import json
from datetime import datetime

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.handle_request("GET")
    
    def do_POST(self):
        self.handle_request("POST")
    
    def do_PUT(self):
        self.handle_request("PUT")
    
    def do_DELETE(self):
        self.handle_request("DELETE")
    
    def handle_request(self, method):
        # 读取请求体内容
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = b''
        if content_length > 0:
            post_data = self.rfile.read(content_length)
        
        # 打印请求信息
        print(f"\n=== 收到 {method} 请求 ===")
        print(f"请求路径: {self.path}")
        print(f"请求方法: {method}")
        print(f"请求时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("请求头信息:")
        
        # 打印所有请求头
        for key, value in self.headers.items():
            print(f"  {key}: {value}")
        
        # 打印请求体内容
        if content_length > 0:
            print(f"请求体内容: {post_data.decode('utf-8')}")
        elif method in ['POST', 'PUT']:
            print("请求体内容: (空)")
        
        # 发送响应状态码
        # self.send_response(200)
        # self.send_header('Content-type', 'application/json; charset=utf-8')
        # self.send_header('Server', 'Python-Test-Server')
        # self.end_headers()
        
        # # 构造并发送响应内容
        # response_data = {
        #     "status": "success",
        #     "message": f"服务器已成功接收 {method} 请求",
        #     "path": self.path,
        #     "method": method,
        #     "timestamp": datetime.now().isoformat(),
        #     "request_body": post_data.decode('utf-8') if content_length > 0 else None
        # }
        
        # # 将响应数据转换为JSON格式
        # response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
        # self.wfile.write(response_json.encode('utf-8'))
        # ... 前面的处理代码 ...
    
        # 简单的响应内容用于测试
        response_text = "Hello from Python Server!"
        
        # 发送响应
        self.send_response(200)
        self.send_header('Content-type', 'text/plain; charset=utf-8')
        self.send_header('Content-Length', str(len(response_text)))
        self.end_headers()
        
        self.wfile.write(response_text.encode('utf-8'))
def run_server():
    server_address = ('192.168.0.172', 8888)
    httpd = HTTPServer(server_address, RequestHandler)
    print("HTTP服务器启动，监听地址 192.168.0.172:8888...")
    print("按 Ctrl+C 停止服务器")
    
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n服务器已停止")
        httpd.server_close()

if __name__ == '__main__':
    run_server()